package com.yuqian.JavaSe.leetcode.easy;

/**
 * 
 * @author yuqian
 *
 */
public class MergeTwoSortedLists {
	public static ListNode mergeTwoLists(ListNode l1, ListNode l2) {
        if(l1!=null&&l2!=null){
           ListNode head = new ListNode(0);
           ListNode result=head;
           while(l1.next!=null||l2.next!=null){
               if(l1.val<l2.val){
                  head.next= l1;
                  if(l1.next!=null){
                	     l1 = l1.next;
                  }else{
                	  head.next.next = l2;
                	  break;
                  }
             
               }else{
                  head.next=l2;
                  if(l2.next!=null){
                	  l2 = l2.next;
                  }else{
                	  head.next.next = l1;
                	  break;
                  }
               }
                head = head.next;
           }
          if(l1.val<l2.val){
                  head.next= l1;
                  head.next.next =l2;
          }else{
                head.next=l2;
                head.next.next =l1;
          }
          return result.next;
        }
        else if(l1!=null&&l2==null){
           return  l1;
        }
        else if(l1==null&&l2!=null){
           return  l2; 
        }
        else{
           return  null; 
        }
    }
	
	public static void main(String[] args) {
		ListNode l1 = new ListNode(1);
		ListNode n2 = new ListNode(3);
		ListNode n4 = new ListNode(4);
		l1.next = n2;
		n2.next = n4;
		ListNode l2 = new ListNode(0);
		ListNode result = mergeTwoLists(l1,l2);
		while(result.next!=null)
		{
			System.out.print(result.val+"  ");
			result = result.next;
		}
	}
}
